import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import axios from 'axios';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';
import { FaArrowLeft, FaSync, FaMagic } from 'react-icons/fa';
import '../styles/SourceDetail.css';

const SourceDetail = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [source, setSource] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [success, setSuccess] = useState('');
  const [monitorLoading, setMonitorLoading] = useState(false);
  const [aiAnalysisLoading, setAiAnalysisLoading] = useState(false);
  const [aiAnalysisResult, setAiAnalysisResult] = useState(null);

  // 获取采集源详情
  useEffect(() => {
    const fetchSourceDetail = async () => {
      try {
        setLoading(true);
        const res = await axios.get(`/api/sources/${id}`);
        setSource(res.data);
        setError(null);
      } catch (err) {
        console.error('获取采集源详情失败:', err);
        setError(err.response?.data?.message || '获取采集源详情失败');
      } finally {
        setLoading(false);
      }
    };

    if (id) {
      fetchSourceDetail();
    }
  }, [id]);

  // 更新采集源
  const handleSubmit = async (values, { setSubmitting }) => {
    try {
      const res = await axios.put(`/api/sources/${id}`, values);
      setSource(res.data);
      setSuccess('采集源更新成功');
      setError(null);
      
      // 3秒后清除成功消息
      setTimeout(() => {
        setSuccess('');
      }, 3000);
    } catch (err) {
      console.error('更新采集源失败:', err);
      setError(err.response?.data?.message || '更新采集源失败');
    } finally {
      setSubmitting(false);
    }
  };

  // 手动监测采集源
  const handleMonitor = async () => {
    try {
      setMonitorLoading(true);
      await axios.post(`/api/sources/${id}/monitor`);
      
      // 刷新采集源数据
      const res = await axios.get(`/api/sources/${id}`);
      setSource(res.data);
      
      setSuccess('采集源监测成功');
      setError(null);
      
      // 3秒后清除成功消息
      setTimeout(() => {
        setSuccess('');
      }, 3000);
    } catch (err) {
      console.error('监测采集源失败:', err);
      setError(err.response?.data?.message || '监测采集源失败');
    } finally {
      setMonitorLoading(false);
    }
  };

  // 使用AI分析页面结构
  const handleAiAnalysis = async (formikProps) => {
    if (!source || !source.listUrl) return;
    
    try {
      setAiAnalysisLoading(true);
      
      // 检查是否是军事或政府网站，默认为这些网站启用代理
      const isMilOrGovSite = source.listUrl.includes('.mil') || source.listUrl.includes('.gov');
      
      // 如果是军事或政府网站，或者用户启用了代理设置，则使用代理
      const useProxy = isMilOrGovSite || (source.proxy && source.proxy.enabled);
      
      const response = await axios.post(`/api/sources/${id}/analyze-with-ai`, { 
        url: source.listUrl,
        useProxy 
      });
      
      setAiAnalysisResult(response.data);
      
      // 如果有formikProps参数，自动应用AI分析结果
      if (formikProps && response.data && response.data.selectors) {
        const { setFieldValue } = formikProps;
        
        // 应用AI分析的选择器结果到表单
        Object.entries(response.data.selectors).forEach(([key, value]) => {
          setFieldValue(`selectors.${key}`, value);
        });
      }
      
      setSuccess('AI分析完成，已找到页面选择器');
      setError(null);
      
      // 3秒后清除成功消息，但保留分析结果
      setTimeout(() => {
        setSuccess('');
      }, 3000);
    } catch (err) {
      console.error('AI分析失败:', err);
      setError('AI分析失败: ' + (err.response?.data?.error || err.message));
    } finally {
      setAiAnalysisLoading(false);
    }
  };

  // 表单验证规则
  const validationSchema = Yup.object({
    name: Yup.string().required('名称为必填项'),
    organization: Yup.string().required('组织名称为必填项'),
    listUrl: Yup.string().url('请输入有效的URL').required('列表URL为必填项'),
    proxy: Yup.object({
      enabled: Yup.boolean(),
      host: Yup.string().when('enabled', {
        is: true,
        then: (schema) => schema.required('代理服务器地址为必填项'),
        otherwise: (schema) => schema
      }),
      port: Yup.number().when('enabled', {
        is: true,
        then: (schema) => schema.required('代理端口为必填项').min(1, '端口必须大于0').max(65535, '端口必须小于65536'),
        otherwise: (schema) => schema
      })
    })
  });

  if (loading) {
    return <div className="loading">加载中...</div>;
  }

  if (!source) {
    return <div className="error-message">采集源不存在或已被删除</div>;
  }

  return (
    <div className="source-detail-container">
      <div className="page-header">
        <button onClick={() => navigate('/sources')} className="back-button">
          <FaArrowLeft /> 返回列表
        </button>
        <h1>采集源详情</h1>
        <div className="header-actions">
          <button 
            onClick={handleMonitor} 
            disabled={monitorLoading}
            className="monitor-button"
          >
            <FaSync className={monitorLoading ? 'spinning' : ''} /> 
            {monitorLoading ? '监测中...' : '立即监测'}
          </button>
        </div>
      </div>

      {error && <div className="error-message">{error}</div>}
      {success && <div className="success-message">{success}</div>}

      {/* AI分析结果 */}
      {aiAnalysisResult && (
        <div className="ai-analysis-result">
          <h3>AI分析结果</h3>
          <p>DeepSeek AI已成功分析页面结构，找到以下选择器:</p>
          <ul>
            <li><strong>列表项选择器:</strong> {aiAnalysisResult.selectors?.listItemSelector || '未找到'}</li>
            <li><strong>姓名选择器:</strong> {aiAnalysisResult.selectors?.nameSelector || '未找到'}</li>
            <li><strong>职位选择器:</strong> {aiAnalysisResult.selectors?.positionSelector || '未找到'}</li>
            <li><strong>图片选择器:</strong> {aiAnalysisResult.selectors?.imageSelector || '未找到'}</li>
            <li><strong>详情链接选择器:</strong> {aiAnalysisResult.selectors?.detailLinkSelector || '未找到'}</li>
          </ul>
          <button 
            className="dismiss-button"
            onClick={() => setAiAnalysisResult(null)}
          >
            关闭
          </button>
        </div>
      )}

      <div className="source-info">
        <div className="info-section">
          <h2>基本信息</h2>
          <div className="info-row">
            <span className="label">状态:</span>
            <span className={`status status-${source.status}`}>
              {source.status === 'active' ? '活跃' : 
               source.status === 'inactive' ? '不活跃' : '错误'}
            </span>
          </div>
          {source.errorMessage && (
            <div className="info-row">
              <span className="label">错误信息:</span>
              <span className="error-text">{source.errorMessage}</span>
            </div>
          )}
          <div className="info-row">
            <span className="label">最后监测:</span>
            <span>{source.lastCrawled ? new Date(source.lastCrawled).toLocaleString() : '从未'}</span>
          </div>
          <div className="info-row">
            <span className="label">创建时间:</span>
            <span>{new Date(source.createdAt).toLocaleString()}</span>
          </div>
        </div>

        <div className="form-section">
          <h2>编辑采集源</h2>
          <Formik
            initialValues={{
              name: source.name || '',
              organization: source.organization || '',
              listUrl: source.listUrl || '',
              detailUrlPattern: source.detailUrlPattern || '',
              selectors: {
                listItemSelector: source.selectors?.listItemSelector || '',
                nameSelector: source.selectors?.nameSelector || '',
                positionSelector: source.selectors?.positionSelector || '',
                imageSelector: source.selectors?.imageSelector || '',
                detailLinkSelector: source.selectors?.detailLinkSelector || ''
              },
              status: source.status || 'active',
              proxy: {
                enabled: source.proxy?.enabled || false,
                host: source.proxy?.host || '',
                port: source.proxy?.port || ''
              }
            }}
            validationSchema={validationSchema}
            onSubmit={handleSubmit}
          >
            {(formikProps) => (
              <Form className="source-form">
                {/* 基本信息 */}
                <div className="form-section">
                  <h3>基本信息</h3>
                  
                  <div className="form-group">
                    <label htmlFor="name">名称</label>
                    <Field type="text" id="name" name="name" className="form-control" />
                    <ErrorMessage name="name" component="div" className="error-message" />
                  </div>
                  
                  <div className="form-group">
                    <label htmlFor="organization">组织名称</label>
                    <Field type="text" id="organization" name="organization" className="form-control" />
                    <ErrorMessage name="organization" component="organization" className="error-message" />
                  </div>
                  
                  <div className="form-group">
                    <label htmlFor="listUrl">列表URL</label>
                    <Field type="text" id="listUrl" name="listUrl" className="form-control" />
                    <ErrorMessage name="listUrl" component="div" className="error-message" />
                  </div>
                  
                  <div className="form-group">
                    <label htmlFor="detailUrlPattern">详情页URL模式 (可选)</label>
                    <Field type="text" id="detailUrlPattern" name="detailUrlPattern" className="form-control" />
                    <div className="form-text">如果详情页URL有特定模式，可以在此指定。例如: https://example.com/bio/{id}</div>
                  </div>
                  
                  <div className="form-group">
                    <label htmlFor="status">状态</label>
                    <Field as="select" id="status" name="status" className="form-control">
                      <option value="active">活跃</option>
                      <option value="inactive">不活跃</option>
                    </Field>
                  </div>
                </div>
                
                {/* 代理设置 */}
                <div className="form-section">
                  <h3>代理设置</h3>
                  <div className="form-text">如果需要通过代理访问该数据源，请配置代理信息</div>
                  
                  <div className="form-group">
                    <div className="checkbox-group">
                      <Field type="checkbox" id="proxy.enabled" name="proxy.enabled" />
                      <label htmlFor="proxy.enabled">启用代理</label>
                    </div>
                  </div>
                  
                  {formikProps.values.proxy.enabled && (
                    <>
                      <div className="form-group">
                        <label htmlFor="proxy.host">代理服务器地址</label>
                        <Field type="text" id="proxy.host" name="proxy.host" className="form-control" placeholder="例如: 192.168.1.1" />
                        <ErrorMessage name="proxy.host" component="div" className="error-message" />
                      </div>
                      
                      <div className="form-group">
                        <label htmlFor="proxy.port">代理端口</label>
                        <Field type="number" id="proxy.port" name="proxy.port" className="form-control" placeholder="例如: 8080" />
                        <ErrorMessage name="proxy.port" component="div" className="error-message" />
                      </div>
                    </>
                  )}
                </div>
                
                {/* 选择器配置 */}
                <h3>选择器配置</h3>
                <div className="form-row">
                  <div className="form-group">
                    <label htmlFor="selectors.listItemSelector">列表项选择器</label>
                    <Field 
                      type="text" 
                      id="selectors.listItemSelector" 
                      name="selectors.listItemSelector" 
                    />
                  </div>
                  
                  <div className="form-group">
                    <label htmlFor="selectors.nameSelector">姓名选择器</label>
                    <Field 
                      type="text" 
                      id="selectors.nameSelector" 
                      name="selectors.nameSelector" 
                    />
                  </div>
                </div>
                
                <div className="form-row">
                  <div className="form-group">
                    <label htmlFor="selectors.positionSelector">职位选择器</label>
                    <Field 
                      type="text" 
                      id="selectors.positionSelector" 
                      name="selectors.positionSelector" 
                    />
                  </div>
                  
                  <div className="form-group">
                    <label htmlFor="selectors.imageSelector">图片选择器</label>
                    <Field 
                      type="text" 
                      id="selectors.imageSelector" 
                      name="selectors.imageSelector" 
                    />
                  </div>
                </div>
                
                <div className="form-group">
                  <label htmlFor="selectors.detailLinkSelector">详情链接选择器</label>
                  <Field 
                    type="text" 
                    id="selectors.detailLinkSelector" 
                    name="selectors.detailLinkSelector" 
                  />
                </div>
                
                <div className="form-actions">
                  <button type="submit" disabled={formikProps.isSubmitting}>
                    {formikProps.isSubmitting ? '保存中...' : '保存更改'}
                  </button>
                </div>
              </Form>
            )}
          </Formik>
        </div>
      </div>
    </div>
  );
};

export default SourceDetail; 